package com.mjt.protal.web.controller;

import com.mjt.dongbao.common.base.result.ResultWrapper;
import com.wf.captcha.ChineseCaptcha;
import com.wf.captcha.utils.CaptchaUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description
 * @Author mjt
 * @Time 2022/1/15
 */
@RestController
@RequestMapping("/captcha")
public class EasyCaptchaController {

    // 日志对象
    Logger logger = LoggerFactory.getLogger(EasyCaptchaController.class);

    @GetMapping("/generator")
    public void generatorCode(HttpServletRequest request, HttpServletResponse response){

        try {

            // 汉字验证码
            ChineseCaptcha chineseCaptcha = new ChineseCaptcha(200, 50);

            // 生成的验证码，与 Session 相关联
            String requestedSessionId = request.getRequestedSessionId();

            logger.info("requestedSessionId: " + requestedSessionId);
            String text = chineseCaptcha.text();
            logger.info("生成的验证码：" + text);

            // 输出验证码
            CaptchaUtil.out(chineseCaptcha, request, response);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @GetMapping("/verifyCaptcha")
    public ResultWrapper verifyCode(String verifyCode, HttpServletRequest request){
        // 校验验证码
        boolean verifyResult = CaptchaUtil.ver(verifyCode, request);

        if (verifyResult){
            logger.info("requestedSessionId: " + request.getRequestedSessionId());
            return ResultWrapper.getSuccessResult().msg("验证码校验通过").build();
        }else {
            logger.info("requestedSessionId: " + request.getRequestedSessionId());
            return ResultWrapper.getSuccessResult().msg("验证码校验不通过").build();
        }
    }


}
